#!/usr/bin/env python
# -*- coding: utf-8 -*-
import cexapi
import datetime
#import time
import re
from dateutil import parser
#from datetime import timedelta
#from datetime import date
#from datetime import time
import calendar

from os import listdir
from os.path import isfile, join

import glob
import platform

import krakenex

showTrue=1
showFalse=0

kraConn = krakenex.API()
kraConn.load_key('kraken.key')

credentialFile = open('cex_credentials.txt', 'r+')

for line in credentialFile:
        resultLine = re.split(';', line)  
        if resultLine[0]=='hannesh':
            apiUser=resultLine[0]
            apiCred1=resultLine[1]
            apiCred2=resultLine[2]      


demo = cexapi.api(apiUser, apiCred1, apiCred2)

def getKraTicker(show):
    kraBitcoin2ltc = kraConn.query_public('Ticker', {'pair':'XXBTXLTC'})
    kraBitcoin2eur = kraConn.query_public('Ticker', {'pair':'XXBTZEUR'})
    if show:
        print "KRA sells 1 BTC for",kraBitcoin2eur['result']['XXBTZEUR']['a'][0], "EUR"
        print "KRA buys  1 BTC for",kraBitcoin2eur['result']['XXBTZEUR']['b'][0], "EUR"
    return {u'Sells':float(kraBitcoin2eur['result']['XXBTZEUR']['a'][0]),u'Buys':float(kraBitcoin2eur['result']['XXBTZEUR']['b'][0])}


def get24HourReward(days):
        
    if platform.system()=="Windows":
        fileSep="\\"
        mypath="C:"+fileSep+"Users"+fileSep+"hassler"+fileSep+"Downloads"
    
    if platform.system()=="Linux":
        fileSep="/"    
        mypath="/home/hannes"+fileSep+"Downloads"
        
    transactionFiles = glob.glob(mypath+fileSep+"transactions*BTC*")
    
    minBalance=10000;
    maxBalance=-1;
    
    retVal=[0,0,0]
    for file in transactionFiles:        
        transactionsFile = open(file, 'r+')
        rewardOf24Hours=0 
        lineCount=0
        numberOfPackages=0   
        for line in transactionsFile:    
            
            resultLine = re.split(',', line)
                        
            datumZeitStr=resultLine[0]
            excpStr="";
            try:
                datumZeit = parser.parse(datumZeitStr)
            
                datumZeitUTSec=calendar.timegm(datumZeit.utctimetuple())
            
                netReward=resultLine[1]
                currency=resultLine[2]
                currBalance=resultLine[3]
            
                
                type=resultLine[4]
                now = datetime.datetime.now()            
                if now<datumZeit+datetime.timedelta(hours = 24*days) and ("mining" in type or "maintenance" in type):
                    #print "withinInterval=\t",resultLine 
                    #if now<datumZeit+datetime.timedelta(hours = 24*days) and ("mining" in type):
                    if minBalance>float(currBalance):
                        minBalance=float(currBalance)
                    if maxBalance<float(currBalance):
                        maxBalance=float(currBalance)                                       
                    rewardOf24Hours=rewardOf24Hours+float(netReward)
                    lineCount=lineCount+1
                    numberOfPackages=numberOfPackages+1
            except:                
                excpStr=excpStr+datumZeitStr
                
    
        #print "#pack/day=\t",round(numberOfPackages/days,1)
        if numberOfPackages>0:
            averageReward=round(10e7*rewardOf24Hours/(numberOfPackages),0)
        else:
            averageReward=0 
        
        #print "maxBalance=",maxBalance, "minBalance=",minBalance, "days=", days
        maxminPerDay=(maxBalance-minBalance)/days       
        retVal=[rewardOf24Hours,numberOfPackages,averageReward,maxminPerDay]
        
                        
    return retVal

def getFromBal(GHSBTC,avl_orders):
    retVal=0
    try:
        retVal=float(bal[GHSBTC][avl_orders])
    except:
        retVal=0
    return retVal
        

days=6.0/1
print "dayIntvl=\t",days
twentyFourHours=get24HourReward(days)
dayReward=twentyFourHours[0]
print "dayReward=\t",dayReward
numberOfPackages=twentyFourHours[1]
averageReward=twentyFourHours[2]
print "24hrRwrd(BTC)=\t",round(dayReward/days,8)
print "avrRwrd(sat)=\t",averageReward    
ticker = demo.ticker()
bal = demo.balance()
ghs_avl=getFromBal('GHS','available')
ghs_orders=getFromBal('GHS','orders')
ghs_tot = ghs_avl+ghs_orders
btc_avl=getFromBal('BTC','available')
btc_orders=getFromBal('BTC','orders')

print "ghs=\t\t",round(ghs_tot,4)
print "avg/ghs(sat)=\t",round(averageReward/ghs_tot,1)    
medBidAsk=(float(ticker['bid'])+float(ticker['ask']))/2
#medBidAsk=0.00654

print "medBidAsk=\t",medBidAsk
currGHSWorth=ghs_tot*medBidAsk
print "currWorth=\t",round(currGHSWorth,5)
kraTicker=getKraTicker(showFalse)
kursEURVXBTC=kraTicker['Buys']
print "workStock(EUR)=\t",round(currGHSWorth*kursEURVXBTC,1)
print "siltStock(EUR)=\t",round((btc_avl+btc_orders)*kursEURVXBTC,1)
print "AllWorth(EUR)=\t",round((currGHSWorth+btc_avl+btc_orders)*kursEURVXBTC,1)
print "        @rate=\t", round(kursEURVXBTC,2), "(EUR/BTC)"
#print "180GHS would cost=\t",round(180*currGHSWorth*kursEURVXBTC/134.15,1)
absVal=round(currGHSWorth*dayReward/(currGHSWorth*days),8)
print "makesPerDay=\t",round(100*dayReward/(currGHSWorth*days),5),"%", "absVal=",absVal
print "mksPDay=\t", round(absVal*kursEURVXBTC,2), "(EUR)"
#print "maxminPerDay=\t",round(twentyFourHours[3],5)

         